<template>


	<div class="merak-container-has-aside" curPageName="sfsadf23424542352">
		<div class="merak-aside">
			<div class="merak-overflow-y">
				<TreeFilter TreeFilter label="title" title="菜单列表" :class="curlevel>2?'merakTree':'merakTree noThree'"
					:data="pageData.menuList" :default-value="page_parents_id" @change="changeTreeFilter"></TreeFilter>
			</div>
		</div>
		<div class="merak-card merak-container-has-search" v-waterMarker>



			<serachBar custom_class="myclass" :search_val=search_val placeholder="权限英文key" :close-plan="true"
				:close-enter="true" :close-advanced="true" @searchEvent="searchFn">


				<template #footer>
					<el-button v-if="curlevel>2" type="primary"
						@click="addForm({id:0})">{{ $t("permission.add_permission") }}
					</el-button>
				</template>
			</serachBar>



			<MerakXTable :columns-by-store="JSON.parse(JSON.stringify(state.columns))" :columns="state.columns"
				:loading="listLoading" :column-type="columnTypeAuth" :data="state.data" :enabled-tree="true"
				:pagination="false" :show-header="false" :enabled-scroll="false" align="left" header-align="left"
				:tree-expand-all="true">
				<template #handler="{row}">
					<div>
						<el-button type="primary" v-if="row.auth.add" link @click="addForm(row)">
							{{ $t("permission.add_permission") }}
						</el-button>
						<el-button type="primary" v-if="row.auth.edit" link @click="editForm(row)">
							{{ $t("permission.edit_permission") }}
						</el-button>
						<el-button type="danger" v-if="row.auth.delete" link @click="deltForm(row)">
							{{ $t("permission.del_permission") }}
						</el-button>
					</div>
				</template>
			</MerakXTable>



		</div>

		<el-drawer modal-class="merak_modal" v-model="menuDrawer" direction="rtl" size="30%">
			<template #header>
				<div class="merak_modal_title">
					{{editFormType==0? $t("permission.add_permission"): $t("permission.edit_permission")}}</div>
			</template>
			<div class="form-box">
				<div>
					<el-form :model="permissionForm" ref="permissionRef" :rules="permissionRules" label-position="top">
						<el-form-item label="权限中文" prop="title">
							<el-input class="qf_input" v-model="permissionForm.title" />
						</el-form-item>
						<el-form-item label="俄文标题" prop="title_ru">
							<el-input class="qf_input" v-model="permissionForm.title_ru" />
						</el-form-item>
						<el-form-item label="权限英文key" prop="auth_key">
							<el-input class="qf_input" v-model="permissionForm.auth_key" />
							<div class="form_tooltip">英文_show/action</div>
						</el-form-item>
						<el-form-item label="后端URL地址">
							<el-input class="qf_input" v-model="permissionForm.url" />
						</el-form-item>
						<el-form-item label="排序" prop="listsort">
							<el-input class="qf_input" v-model="permissionForm.listsort" />
						</el-form-item>
					</el-form>
				</div>


			</div>
			<template #footer>
				<el-button v-if="editFormType=='0'" type="default"
					@click="saveForm('0',permissionRef)">{{ $t("merak.save_continue") }} </el-button>
				<el-button type="primary" @click="saveForm('1',permissionRef)">{{ $t("merak.save") }}</el-button>
				<el-button v-if="editFormType=='1'" type="default"
					@click="menuDrawer=false">{{ $t("merak.cancel") }}</el-button>
			</template>
		</el-drawer>
	</div>









</template>

<script setup lang="ts" name="Permission">
	const zz = ref("0")
	zz.value = "5"



	import { onMounted, reactive, ref, getCurrentInstance } from "vue";
	import { ElMessage, FormInstance, FormRules } from "element-plus";
	import MerakXTable, { MerakXTableInstance, MerakXTableColumn } from "@/components/MerakXTable";
	import TreeFilter from "@/components/TreeFilter/index.vue";
	import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';
	import serachBar from "@/components/SearchBar/index";
	import { getAllMenuListApi, authSaveApi, getAuthListApi, getDelAuthApi } from "@/api/modules/permission";
	import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, confirmSuccessMsg } from "@/utils/messageUtils";
	import { getLocationParams } from "@/utils/index";
	import I18n from "@/languages/index";




	const $t = I18n.global.t;
	const columnTypeAuth = reactive([]);
	if ($t("lang") == 'ru') {
		Object.assign(columnTypeAuth, [{ type: 'handle', width: 400, slot: 'handler' }]);
	} else {
		Object.assign(columnTypeAuth, [{ type: 'handle', width: 300, slot: 'handler' }]);
	}

	let search_val = ref("");
	const searchFn = (e) => {
		console.log(e)
		// e.searchVal
		state.params.key_words = e.search;
	}
	const { proxy } = getCurrentInstance();
	const menuDrawer = ref(false);//弹窗控制
	const listLoading = ref(true);//弹窗控制

	const formTypeValue = ref('');//表单类型（二级/三级）
	const pageData = reactive({
		menuList: [],//全部菜单
		stairList: [],//一级菜单
		secondList: [],//二级菜单
		threeList: [],//三级菜单
	});
	const permissionRef = ref<FormInstance>();
	const page_parents_id = ref("");
	//获取权限列表
	const getlist = () => {
		listLoading.value = true;
		if (!page_parents_id.value) {
			page_parents_id.value = '';
		}
		getAuthListApi({ id: page_parents_id.value }).then(res => {
			listLoading.value = false;
			if (res.code == ResultEnum.SUCCESS) {
				const list = res.data.list;
				state.data = list;

			}
		})
	}

	onMounted(async () => {
		const { data } = await getAllMenuListApi();
		page_parents_id.value = "13"
		const newUrl = new URL(window.location.href);
		console.log(newUrl)
		let urlId = getLocationParams(newUrl.href, 'id');
		console.log(urlId)
		page_parents_id.value = urlId;
		pageData.menuList = data.list;
		let newList : any = [];
		data.list.map((stairItem : any, stairIndex : number) => {
			newList.push(stairItem)
		})
		pageData.stairList = newList

		getlist()






	});




	const curlevel = ref(3);
	const permissionForm = ref({//二级菜单数据
		id: "",
		title: "",
		title_ru: "",
		url: "",
		auth_key: "",
		parent_id: page_parents_id.value,
		listsort: 1,
	})

	const stairValue = reactive({ departmentId: "1" });

	const changeTreeFilter = (row) => {
		page_parents_id.value = row.id;
		curlevel.value = row.level;

		if (curlevel.value < 3) {
			return false;
		}



		// 构建新的URL
		const newUrl = new URL(window.location.href);
		//console.log(newUrl)
		newUrl.searchParams.set('id', row.id);
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());




		getlist()


	};




	const editFormType = ref(0); //0新增 1编辑
	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}

	//新增
	const addForm = (formType : any) => {
		//formTypeValue.value = formType
		//console.log(formTypeValue.value)
		resetForm(permissionRef.value)
		editFormType.value = 0;
		permissionForm.value = {
			id: 0,
			title: "",
			title_ru: "",
			url: "",
			auth_key: "",
			parent_id: "",
			listsort: "1"
		}

		if (formType.id != "0") {
			//formType.id
			permissionForm.value.parent_id = formType.id;
		} else {
			permissionForm.value.parent_id = page_parents_id.value;
		}
		menuDrawer.value = true;
	}
	//编辑
	const editForm = (row : any) => {
		resetForm(permissionRef.value)
		const rowt = JSON.parse(JSON.stringify(row))
		editFormType.value = 1;
		permissionForm.value = rowt;
		menuDrawer.value = true;
	}

	//删除
	const deltForm = (row : any) => {
		confirmWarningMsg({
			msg: "确认删除吗？删除当前权限子集也会删除",
			callback: val => {
				if (val == "confirm") {
					getDelAuthApi({ id: row.id }).then(res => {
						if (res.code == 2000) {
							successMsg('删除成功');
							getlist()
						} else {
							warnMsg(res.message);
						}
					})
				}
			}
		});
	}
	//保存提交权限
	const saveForm = (typebtn : string, formEl : any) => {

		if (!formEl) return
		formEl.validate((valid) => {
			if (valid) {
				authSaveApi(permissionForm.value).then(res => {
					if (res.code == 2000) {
						successMsg('保存成功');
						getlist()
						if (typebtn == '0') {

							const cur_parent_id = permissionForm.value.parent_id;
							permissionForm.value = {
								id: 0,
								title: "",
								title_ru: "",
								url: "",
								auth_key: "",
								parent_id: cur_parent_id,
								listsort: "1"
							}

						} else {
							menuDrawer.value = false;
						}
					} else {
						warnMsg(res.message);
					}
				})



			} else {
				warnMsg(res.message);
				return false
			}
		})













		const type = typebtn;
		//保存继续录入
		if (type == 0) {

		}
		//仅保存
		if (type == 1) {

		}
		menuDrawer.value = true;
	}


	const validateAuthKey = (rule : any, value : any, callback : any) => {
		if (value === '') {
			callback(new Error(proxy.$t("main.requiredMsg")))
		} else {
			let reg = /^[a-zA-Z]+_[a-zA-Z]+$/

			if (reg.test(value)) {

			} else {
				callback(new Error("必须是英文+下划线+英文  demo_show/action"))
			}
			callback()
		}
	}

	const permissionRules = reactive({
		title: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		title_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		auth_key: [{ required: true, validator: validateAuthKey, trigger: "blur" }],
		url: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
	});
	const state = reactive<{
		columns : MerakXTableColumn[];
		data : any;
	}>({
		columns: [
			{ field: "auth_name", title: "获取权限名字 auth_name" },
			{ field: "title", title: "权限中文", treeNode: true },
			{ field: "title_ru", title: "权限俄文" },
			{ field: "auth_key", title: "权限key" },
			{ field: "url", title: "后端URL地址" },

			{ field: "id", title: "id", width: 80 },
			{ field: "listsort", title: "排序", width: 90 },
		],
		data: [
			// 	{
			// 		id: "1",
			// 		title: "新增人员",
			// 		title_ru: "新增人员（俄）",
			// 		auth_key: "add_show",
			// 		url: "/menu/ajxios",
			//     children:[
			//       {
			//       id: "2",
			//       title: "修改人员姓名1",
			//       title_ru: "修改人员姓名1（俄）",
			//       auth_key: "editname_action",
			//       url: "/menu/ajxios",
			//     },
			//     {
			//       id: "3",
			//       title: "修改人员姓名2",
			//       title_ru: "修改人员姓名2（俄）",
			//       auth_key: "editname_show",
			//       url: "/menu/ajxios",
			//     },
			//     {
			//       id: "4",
			//       title: "修改人员性别",
			//       title_ru: "新增人员（俄）",
			//       auth_key: "editsex_action",
			//       url: "/menu/ajxios",
			//     }
			// ]
			// 	},

			// 	{
			// 		id: "5",
			//     title: "修改人员性别",
			//     title_ru: "新增人员（俄）",
			//     auth_key: "editsex_action",
			//     url: "/menu/ajxios",
			// 	},
		]
	});






	const handlePageChange : MerakXTableInstance["onPage-change"] = ({ currentPage, pageSize }) => {
		console.log(currentPage, pageSize);
	};
</script>

<style scoped lang="scss">
	@import "./index.scss";

	:deep(.filter.noThree .el-tree-node.is-current .el-tree-node__content) {
		background-color: #fff !important;
	}

	:deep(.filter.noThree .el-scrollbar .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content .el-tree-node__expand-icon) {
		color: var(--el-tree-expand-icon-color) !important;
	}

	:deep(.filter.noThree .el-scrollbar .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content .el-tree-node__label) {
		color: var(--el-tree-text-color) !important;
	}
</style>